//
//  JXReviewListController.m
//  JiaoX
//
//  Created by yinqy on 15/1/5.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "JXReviewListController.h"
#import "CheckLabel.h"
#import "JXBaseRequest.h"
#import "HomeDataTool.h"
#import "HomeTabInfo.h"
#import "JXNewTopicCtl.h"
#import "SelfDataTool.h"
#import "JXLoginRegistCheckController.h"
#import "JXPostsDetailCtl.h"
#import "ShareOrderPopView.h"
#import "HomeReviewsCell.h"
#import "CustomShowView.h"
#import "SGFocusImageItem.h"
#import "HomeBanner.h"
#import "SGFocusImageFrame.h"
#import "JXWebViewController.h"
#import "MJRefresh.h"
#import "JXReviewsController.h"
#import "JXNavigationController.h"

@interface JXReviewListController ()<SGFocusImageFrameDelegate,UITableViewDelegate,UITableViewDataSource,ShareOrderPopViewDelegate>
{
    NSMutableArray *_bannerArray;
    NSMutableArray *_reviewsArray;
    int _pageNum;
    SGFocusImageFrame *_bannerView;
    UIButton *_toTopBtn;
    
    
    UIButton *_sunSingleBtn;
}
@property(nonatomic,strong)CheckLabel *checkLabel;
@property(nonatomic,strong)UITableView *tableView;

@end

@implementation JXReviewListController

+(instancetype)initWithCheckLabel:(CheckLabel *)checkLabel{
    JXReviewListController *controller = [[self alloc]init];
    controller.checkLabel = checkLabel;
    return controller;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _bannerArray = [NSMutableArray array];
    _reviewsArray = [NSMutableArray array];
    
    _tableView = [[UITableView alloc]init];
    _tableView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.height-NavHeight-49);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView setSeparatorColor:JXColor(242, 242, 242)];
    [self.view addSubview:_tableView];
    
    _toTopBtn = [[UIButton alloc]init];
    _toTopBtn.frame = CGRectMake(JXScreenW-50, _tableView.height-60, 40, 40);
    [_toTopBtn addTarget:self action:@selector(toTop:) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:_toTopBtn aboveSubview:self.tableView];

    
    
    if ([[NSString stringWithFormat:@"%@",self.checkLabel.id] isEqualToString:KEY_SUNSINGLE_ID]) {
        _sunSingleBtn = [[UIButton alloc]init];
        _sunSingleBtn.frame = CGRectMake((JXScreenW-40)/2, _tableView.height-50, 40, 40);
        [_sunSingleBtn setBackgroundColor:[UIColor blackColor]];
        [_sunSingleBtn setAlpha:0.7];
        [_sunSingleBtn setImage:IMG(@"ic_share_prod") forState:UIControlStateNormal];
        [_sunSingleBtn addTarget:self action:@selector(shareBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_sunSingleBtn.layer setCornerRadius:_sunSingleBtn.width/2];
        [_sunSingleBtn.layer setMasksToBounds:YES];
        [self.view insertSubview:_sunSingleBtn aboveSubview:self.tableView];
    }
    
    [self.tableView addHeaderWithTarget:self action:@selector(headerRefresh)];
}

-(void)toTop:(UIButton *)toTopBtn{
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
                          atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

-(void)headerRefresh{
    if ([[NSString stringWithFormat:@"%@",self.checkLabel.id] isEqualToString:KEY_SUNSINGLE_ID]) {
        [self getData:@""];
    }else{
        _pageNum = 1;
        [self requestDataWithPageNum:_pageNum];
    }
}

-(void)footerRefresh{
    if ([[NSString stringWithFormat:@"%@",self.checkLabel.id] isEqualToString:KEY_SUNSINGLE_ID]) {
        HomeReviews *reviews = [_reviewsArray lastObject];
        if (reviews) {
            [self getData:reviews.createTime];
        }else{
            [self getData:@""];
        }
    }else{
        _pageNum ++;
        [self requestDataWithPageNum:_pageNum];
    }
}


-(void)checkRequestData{
    if(!_reviewsArray.count){
        [self.tableView headerBeginRefreshing];
    }
}

-(void)requestDataWithPageNum:(int)pageNum{
    JXBaseRequest *request = [[JXBaseRequest alloc]init];
    NSDictionary *dic = [request keyValues];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
    [params setObject:_checkLabel.id forKey:@"labelId"];
    [params setObject:[NSString stringWithFormat:@"%d",pageNum] forKey:@"pageNum"];
    
    [HomeDataTool homeDataInfoWithParam:params success:^(HomeTabInfo *result) {
        //数据获取完毕
        [Utils refreshComplete:self.tableView];
        if(!result.code){
            [self setData:result pageNum:pageNum];
        }else{
            //加载失败
            UIViewController *c = [[self.view superview] viewController];
            [DialogUtils showTipsWithView:c.navigationController.view String:result.data];
        }
        
    } failure:^(NSError *error) {
        //加载失败
        [Utils refreshComplete:self.tableView];
        [DialogUtils showTipsWithView:[UIApplication sharedApplication].keyWindow String:@"加载失败"];
    }];
}

-(void)getData:(NSString *)createTime{
    [HomeDataTool getSunSignleWithSunSingleId:KEY_SUNSINGLE_ID productId:@"" createTime:createTime success:^(HomeTabInfo *result) {
        //数据获取完毕
        [Utils refreshComplete:self.tableView];
        if(!result.code){
            [self setData:result createTime:createTime];
        }else{
            //加载失败
            UIViewController *c = [[self.view superview] viewController];
            [DialogUtils showTipsWithView:c.navigationController.view String:result.data];
        }
    } failure:^(NSError *error) {
        //加载失败
        [Utils refreshComplete:self.tableView];
        [DialogUtils showTipsWithView:[UIApplication sharedApplication].keyWindow String:@"加载失败"];
    }];
}

-(void)setData:(HomeTabInfo *)result pageNum:(int)pageNum{
    [_toTopBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:result.backTopImg] forState:UIControlStateNormal];
    if(pageNum==1){
        [_bannerArray removeAllObjects];
        [_reviewsArray removeAllObjects];
        [self.tableView addFooterWithTarget:self action:@selector(footerRefresh)];
    }else{
        if(result.reviewsList.count==0){
            //去掉上拉加载
            [self.tableView removeFooter];
        }
    }
    [_bannerArray addObjectsFromArray:result.bannerList];
    [_reviewsArray addObjectsFromArray:result.reviewsList];
    
    [self.tableView reloadData];
    [self setBannerData];
}

-(void)setData:(HomeTabInfo *)result createTime:(NSString *)createTime{
    [_toTopBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:result.backTopImg] forState:UIControlStateNormal];
    if(ISBLANK(createTime)){
        [_bannerArray removeAllObjects];
        [_reviewsArray removeAllObjects];
        [self.tableView addFooterWithTarget:self action:@selector(footerRefresh)];
    }else{
        if(result.reviewsList.count==0){
            //去掉上拉加载
            [self.tableView removeFooter];
        }
    }
    [_bannerArray addObjectsFromArray:result.bannerList];
    [_reviewsArray addObjectsFromArray:result.reviewsList];
    [self.tableView reloadData];
    [self setBannerData];
}

-(void)setBannerData{
    self.tableView.tableHeaderView = nil;
    if(!_bannerArray.count)return;
    
    NSMutableArray *itemArray = [NSMutableArray arrayWithCapacity:_bannerArray.count+2];
    
    for (int i = 0; i < _bannerArray.count; i++)
    {
        HomeBanner *banner = _bannerArray[i];
        SGFocusImageItem *item = [[SGFocusImageItem alloc] initWithTitle:banner.url image:banner.bannerImg tag:i];
        [itemArray addObject:item];
    }
    
    if(_bannerArray.count>1){
        HomeBanner *startBanner = _bannerArray[_bannerArray.count-1];
        SGFocusImageItem *startItem = [[SGFocusImageItem alloc] initWithTitle:startBanner.url image:startBanner.bannerImg tag:_bannerArray.count-1];
        [itemArray insertObject:startItem atIndex:0];
        
        HomeBanner *endBanner = _bannerArray[0];
        SGFocusImageItem *endItem = [[SGFocusImageItem alloc] initWithTitle:endBanner.url image:endBanner.bannerImg tag:_bannerArray.count-1];
        [itemArray addObject:endItem];
    }
    
    
    SGFocusImageFrame *bannerView = [[SGFocusImageFrame alloc] initWithFrame:CGRectMake(0, 0, JXScreenW, JXScreenW*0.5) delegate:self imageItems:itemArray isAuto:NO];
    [bannerView scrollToIndex:0];
    self.tableView.tableHeaderView = bannerView;
    _bannerView = bannerView;
}


#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(_reviewsArray.count){
        tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }else{
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _reviewsArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeReviewsCell *cell = [HomeReviewsCell cellWithTableView:tableView];
    [cell setReviews:_reviewsArray[indexPath.row]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return HomeReviewsViewHeight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UIViewController *c = [[self.view superview] viewController];
    HomeReviews *reviews = _reviewsArray[indexPath.row];
    if ([[NSString stringWithFormat:@"%@",self.checkLabel.id] isEqualToString:KEY_SUNSINGLE_ID]) {
        //是晒单
        [c.navigationController pushViewController:[[JXPostsDetailCtl alloc] initWithPostId:reviews.reviewsId] animated:YES];
    }else{
        [c.navigationController pushViewController:[JXReviewsController initWithReviewId:reviews.reviewsId title:reviews.labelTitle reviewsTitle:reviews.title shareImgUrl:reviews.img] animated:true];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if(scrollView.contentOffset.y>scrollView.height*2){
        [_toTopBtn setHidden:NO];
    }else{
        [_toTopBtn setHidden:YES];
    }
}

-(void)viewDidLayoutSubviews
{
    [Utils setSeparatorInsetWithTableView:self.tableView insets:UIEdgeInsetsMake(0,JXPublicInset,0,0)];
}

- (void)foucusImageFrame:(SGFocusImageFrame *)imageFrame didSelectItem:(SGFocusImageItem *)item
{
    UIViewController *c = [[self.view superview] viewController];
    [Utils dealUrlWithController:c url:item.title title:@"" fromWebView:false];
}


-(void)shareBtnClick:(UIButton *)btn{
    if (TOKEN) {
        [self getShareOrderData];
    }else{
        //登录
        UIViewController *c = [[self.view superview] viewController];
        JXNavigationController *nav = [[JXNavigationController alloc]initWithRootViewController:[[JXLoginRegistCheckController alloc]init]];
        [c.navigationController presentViewController:nav animated:YES completion:^{}];
//        JXLoginRegistCheckController *log = [[JXLoginRegistCheckController alloc]init];
//        UIViewController *c = [[self.view superview] viewController];
//        [c.navigationController pushViewController:log animated:YES];
    }
    
}

//以下是晒单需要的方法

-(void)getShareOrderData{
    JXBaseRequest *request = [[JXBaseRequest alloc]init];
    NSDictionary *dic = [request keyValues];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
    [params setObject:@"1" forKey:@"pageIndex"];
    MBProgressHUD *loding = [DialogUtils showLoadingWithView:self.view];
    [loding show:YES];
    [SelfDataTool getShareOrderList:params success:^(ShareProductRes *result) {
        [loding hide:YES];
        ShareOrderPopView *shareOrderView =  [[ShareOrderPopView alloc]init];
        shareOrderView.width = JXScreenW-60;
        [shareOrderView setDelegate:self];
        //设置数据
        [shareOrderView setShareProductData:result];
        //显示在弹出窗体中
        CustomShowView *showView = [[CustomShowView alloc]initWithCustomView:shareOrderView];
        [showView showWithanim:NO];
    } failure:^(NSError *error) {
        [loding hide:YES];
        [DialogUtils showTipsWithView:self.view String:@"加载晒单数据失败"];
    }];
}

-(void)shareOrder:(CartProdSub *)prod{
    UIViewController *c = [[self.view superview] viewController];
    JXNewTopicCtl *ctl = [[JXNewTopicCtl alloc]initWithSharedId:KEY_SUNSINGLE_ID prodId:prod.prodId ProdName:prod.prodName];
    [c.navigationController pushViewController:ctl animated:YES];
}

@end
